package com.java.androidmarket.listener;

import com.java.androidmarket.entity.Order;
import com.java.androidmarket.entity.OrderGoods;
import com.java.androidmarket.service.KillStockService;
import com.java.androidmarket.service.OrderGoodsService;
import com.java.androidmarket.service.OrderService;
import com.java.androidmarket.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * description:
 * author:张腾
 * date:2021-05-15
 */

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private StockService stockService;
    @Autowired
    private KillStockService killStockService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    @Transactional
    public void onMessage(Message message, byte[] pattern) {

        String orderIdS = message.toString();
        if (orderIdS.substring(0,8).equals("OOTOrder")){
            String orderSn = String.valueOf(orderIdS.substring(9));

            int orderId = orderService.getOrderId(orderSn);
            //恢复商品库存
            List<OrderGoods> orderGoodslist = orderGoodsService.getOrderGoods(orderId);
            for (OrderGoods orderGoods : orderGoodslist) {
                stockService.reLock(orderGoods.getGoodsId(),orderGoods.getGoodsNum());
            }
            orderService.deleteRedis(orderSn);
            //修改订单状态
            Order order = new Order();
            order.setOrderSn(orderSn);
            order.setOrderStatus(-1); //设置为超时
            orderService.changeStatus(order);
            System.out.println("key值："+orderIdS+"已过期");
        }

        else if (orderIdS.substring(0,12).equals("OOTKillOrder")){
            String orderSn = String.valueOf(orderIdS.substring(13));

            int orderId = orderService.getOrderId(orderSn);
            //恢复商品库存
            List<OrderGoods> orderGoodslist = orderGoodsService.getOrderGoods(orderId);
            for (OrderGoods orderGoods : orderGoodslist) {
                killStockService.reLock(orderGoods);
            }
            orderService.deleteRedis(orderSn);
            //修改订单状态
            Order order = new Order();
            order.setOrderSn(orderSn);
            order.setOrderStatus(-1); //设置为超时
            orderService.changeStatus(order);
            System.out.println("key值："+orderIdS+"已过期");
        }
    }
}
